/**
 * @description Manage group event reception, interact with EventDispatcher
 */

/**
 * @param event Object describing the remote event.
 */
function receiveEvent(event){
    if(event.group != GROUP){
        alert("Context error"); //Should not occur ...
    }else{ 
        var eventData = jQuery.evalJSON(event.data);
        if(event.widgetId == "GUI" && USERNAME != event.user){// Prevent receiving self's event (Consistency...)
            if(event.event =="add"){
                widgetFactory.requestManifest(eventData.widget,{
                    requiresSync : false
                });
            }else if(event.event == "delete"){
                $('#widgetContainer_' + eventData.widget).remove();
                delete widgetFactory.widgets[eventData.widget];
            }else if(event.event == "move"){
                var serial = eventData.serial.split("&");
                for (var i = 0 ; i < serial.length ; i++){
                    if(serial != ''){
                        var col = serial[i].split("[]=")[0];
                        var widgetContainer = serial[i].split("[]=")[1];
                        if($('#' + widgetContainer).length){
                            if(serial[i-1] && serial[i-1].split("[]=")[0] == col)
                                $('#'+widgetContainer).insertAfter('#'+serial[i-1].split("[]=")[1]);
                            else
                                $('#'+col).get(0).insertBefore($('#'+widgetContainer).get(0), $('#'+col).get(0).firstChild);
                        }
                    }
                }
            }else if(event.event == "minimize"){
                widgetFactory.widgets[eventData.widget].__showHide();
            }
        }else if(event.widgetId == "PREFERENCES" && USERNAME != event.user){
            var iframe = document.getElementById('iframe_'+event.event);
			var doc = iframe.contentWindow || iframe.contentDocument;
            for (var v in eventData){
                widgetFactory.widgets[event.event].manifest['preferences'][v]['value'] = eventData[v];
            }
            doc.location.reload();
        }else if(event.widgetId != 'PREFERENCES' && event.widgetId != 'GUI'){
            eventDispatcher.handleRemoteFiring(eventDispatcher.listeners[event.widgetId][event.event], "REMOTE", event.event, eventData, event.user);
        }
    }
}
